package cn.com.jinhao.provider.business.service.impl;

import cn.com.jinhao.hotline.commons.exception.BusinessErrorException;
import cn.com.jinhao.hotline.commons.vo.business.record.TapeRequest;
import cn.com.jinhao.hotline.commons.vo.business.record.list.TapeRequestVO;
import cn.com.jinhao.provider.business.entity.Tape;
import cn.com.jinhao.provider.business.mapper.TapeMapper;
import cn.com.jinhao.provider.business.service.TapeService;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * hotline-spring-cloud
 * <p>Description: 录音文件业务逻辑</p>
 *
 * @author ShaneMew
 * @version 1.0
 * @date 2020/6/2
 * @since 2020/6/2
 */
@Service
public class TapeServiceImpl implements TapeService {
    @Resource
    TapeMapper tapeMapper;

    @Override
    public List<Tape> queryTapsByEventCode(String eventCode) {
        Example example = new Example(Tape.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("eventCode", eventCode);
        return tapeMapper.selectByExample(example);
    }

//    @Override
//    public void update(List<TapeRequest> tapeRequestList) throws Exception {
//        String eventCode = tapeRequest.getEventCode();
//        // 先删除所有事件的录音
//        Example example = new Example(Tape.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("eventCode", eventCode);
//        tapeMapper.deleteByExample(example);
//
//        Tape tape = new Tape();
//        BeanUtil.copyProperties(tapeRequest, tape);
//        // 重新增加录音文件
//        int result = tapeMapper.insert(tape);
//        if (result == 0) {
//            throw new BusinessErrorException("更新录音文件失败!");
//        }
//    }

    @Override
    public void delete(String eventCode) throws Exception {
        Example example = new Example(Tape.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("eventCode", eventCode);
        int result = tapeMapper.deleteByExample(example);
        if (result == 0) {
            throw new BusinessErrorException("删除录音文件失败!");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatch(List<TapeRequest> tapeRequestList) throws Exception {
        List<Tape> tapeList = new ArrayList<>();
        tapeRequestList.forEach(item -> {
            Tape tape = new Tape();
            BeanUtil.copyProperties(item, tape);
            tapeList.add(tape);
        });
        int result = tapeMapper.insertList(tapeList);
        if (result == 0) {
            throw new BusinessErrorException("增加录音文件失败!");
        }
    }
}
